#!/usr/bin/perl

# script which allows the communication between the AMS or xrootd server
# and an external Mass Storage System, in this case another xrootd cluster
# F.Furano, CERN, Nov 2007
# From previous rfio work by J-Y Nief, CC-IN2P3, March 2004
#
#
# Fix: avoid that a statx request gets redirected to the same host asking for it
#      F.Furano, CERN, Sept 2008
#

use Time::Local;
use XrdClientAdmin;

$blocksz = 1024; # blocksize = 1024 B
%Month = ('Jan', 0, 'Feb', 1, 'Mar', 2, 'Apr', 3, 'May', 4, 'Jun', 5,
	  'Jul', 6, 'Aug', 7, 'Sep', 8, 'Oct', 9, 'Nov', 10, 'Dec', 11);

$command = $ARGV[0];


if ( $command eq "create" ) {
    $file = $ARGV[1];
    $mode = $ARGV[2];
    $com = "touch /tmp/emptyfile";
    $rc = system($com);

    if ($rc == 0) {
	$com = "xrdcp -f /tmp/emptyfile ".$file;
	$rc = system($com);
    }

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "dlist" ) {
    $dir = $ARGV[1];
    XrdClientAdmin::XrdInitialize("root:\/\/".GetClusterPrefix($dir)."//dummy", "DebugLevel -1\nConnectTimeout 30\nConnectTimeoutWan 30\nFirstConnectMaxCnt 3\nMaxRedirectcount 10");
    @ans=XrdClientAdmin::XrdStat(GetPureFilename($dir));
    if ( ($ans[1] eq $ans[2]) && ($ans[2] <= 0) ) {
	$rc = -1;
    }
    else {
	$list=XrdClientAdmin::XrdDirList(GetPureFilename($dir));
	$rc = 0;
    }

    XrdClientAdmin::XrdTerminate();

    $ret = $rc."\n".$list;
    print $ret;
    exit;
}

if ( $command eq "mv" ) {
    $oldname = $ARGV[1];
    $newname = $ARGV[2];
    XrdClientAdmin::XrdInitialize("root:\/\/".GetClusterPrefix($oldname)."//dummy", "DebugLevel -1\nConnectTimeout 30\nConnectTimeoutWan 30\nFirstConnectMaxCnt 3\nMaxRedirectcount 10");
    $rc = XrdClientAdmin::XrdMv(GetPureFilename($oldname), GetPureFilename($newname));
    XrdClientAdmin::XrdTerminate();

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "rm" ) {
    $file = $ARGV[1];
    XrdClientAdmin::XrdInitialize("root:\/\/".GetClusterPrefix($file)."//dummy", "DebugLevel -1\nConnectTimeout 30\nConnectTimeoutWan 30\nFirstConnectMaxCnt 3\nMaxRedirectcount 10");
    $rc = XrdRm(GetPurefilename($file));
    XrdClientAdmin::XrdTerminate();

    $ret = $rc."\n";
    print $ret;
    exit;
}

if ( $command eq "statx" ) {
    $stats = "";
    $file = $ARGV[1];
    $rc = -1;

    print "we are using statx\n";

    $clustname = GetClusterPrefix($file);
    if ( !($clustname eq "") ) {

       $rc = 0;
       XrdClientAdmin::XrdInitialize("root:\/\/".$clustname."//dummy", "DebugLevel -1\nConnectTimeout 30\nConnectTimeoutWan 30\nFirstConnectMaxCnt 3\nMaxRedirectcount 10");
       $fn = GetPureFilename($file);
       $clustid = `head -n 4 $ENV{XRDBASEDIR}/admin/server/cmsd.pid | tail -n 1`;

       if ( $clustid =~ m/&cn\=(.*)/ ) {
          $clustid = $1;
       }

       if ( !($clustid eq "") ) {
          if ($fn =~ m/\?/) {
             $fn = $fn."&tried=+".$clustid;
          }
          else {
             $fn = $fn."?&tried=+".$clustid;
          }
       }

       @ans = XrdClientAdmin::XrdStat($fn);
       XrdClientAdmin::XrdTerminate();

#       print "ans $ans[1] $ans[2] $ans[3] $ans[4] \n\n";

#       print "$file\n";
      @fileArray = split(/\/\//, $file);
#       print "alien_ls -ln /$fileArray[2]\n";
      $lsOut = `alien_ls -ln /$fileArray[2]`;
      if ( ($lsOut eq "") ) {
	$ret = -1;
	exit;
      }

      @lsOutArray = split(/\s+/, $lsOut);
#       print "[0]=$lsOutArray[0] [1]=$lsOutArray[1] [2]=$lsOutArray[2] [3]=$lsOutArray[3] ";
#       print "[4]=$lsOutArray[4] [5]=$lsOutArray[5] [6]=$lsOutArray[6] [7]=$lsOutArray[7] [8]=$lsOutArray[8] [9]=$lsOutArray[9]\n";

#        $ftype="f";
#        $blkcnt = int($ans[2] / 1024);
#        $stats = $ftype." rwxr-x--- 0 0 0 $ans[4] $ans[4] $ans[4] $ans[2] 1024 $blkcnt";

       $ftype="f";
       $blkcnt = int($lsOutArray[3] / $blocksz);
       $stats = $ftype." rwxr-x--- 0 0 0 $ans[4] $ans[4] $ans[4] $lsOutArray[3] $blocksz $blkcnt";
#       print "$stats\n";
       if ( ($ans[1] eq $ans[2]) && ($ans[2] <= 0) ) {
          $rc = -1;
       }

    }
 
    $ret = $rc."\n".$stats;
    print "$ret\n";
    exit;
}



sub GetClusterPrefix {
    my ($url) = @_;

    if ($url =~ "root\:\/\/(.*)\/\/") {
       return $1;
    }
    return "";
}


sub GetPureFilename {
    my ($url) = @_;
    if ($url =~ "root\:\/\/(.*)\/\/(.*)") {
       return "\/$2";
    }
    return $url;
}

sub unixTime {
    @input = @_;
    $mon = $Month{$input[4]};
    $mday = $input[5];
    ($hours, $min, $sec) = split /:/, $input[6];
    $year = $input[7] - 1900;
    $time = timelocal($sec,$min,$hours,$mday,$mon,$year);
    return $time;
}


